<?php
class Template {
	public $config_smarty;
	public $object;
	private $template_dir; //提供模板切换支持
	private $compile_dir;
	private $cache_dir;
	
	function __construct($sub = '') {
		if(DEBUG === TRUE){
			echo '--- View construct!' . '<br/>';
		}
		$this->setTemplate ( $sub );
		$this->initialize ();
	}
	
	private function initialize() {
		$tpl = Mid::smarty();
		$tpl->template_dir = $this->template_dir;
		$tpl->compile_dir = $this->compile_dir;
		$tpl->cache_dir = $this->cache_dir;
		$tpl->left_delimiter = $this->config_smarty ['left_delimiter'];
		$tpl->right_delimiter = $this->config_smarty ['right_delimiter'];
		$tpl->caching = $this->config_smarty ['caching'];
		$tpl->force_compile = $this->config_smarty ['force_compile'];
		$this->object = $tpl;
	}
	
	private function setTemplate($sub) {
		if (! isset ( $GLOBALS ['config'] ['smarty'] )) {
			exit ( ' variable $config[smarty] not found! Please check and retry! ' );
		}
		$this->config_smarty = $GLOBALS ['config'] ['smarty'];
		//Directory set
		if (! $sub) {
			$sub = $this->config_smarty ['default'];
		}
		$tempate_dir = $this->config_smarty ['template_dir'] . $sub;
		if (! is_dir ( $tempate_dir ) && ! @mkdir ( $tempate_dir )) {
			exit ( 'Smarty Template directory ' . $tempate_dir . ' can not be created!' );
		}
		$this->template_dir = $tempate_dir;
		
		$compile_dir = $this->config_smarty ['compile_dir'] . $sub;
		if (! is_dir ( $compile_dir ) && ! @mkdir ( $compile_dir )) {
			exit ( 'Smarty Compile directory ' . $compile_dir . ' can not be created!' );
		}
		$this->compile_dir = $compile_dir;
		
		$cache_dir = $this->config_smarty ['cache_dir'] . $sub;
		if (! is_dir ( $cache_dir ) && ! @mkdir ( $cache_dir )) {
			exit ( 'Smarty Cache directory ' . $cache_dir . ' can not be created!' );
		}
		$this->cache_dir = $cache_dir;
	}
	
	public function change($sub = '') {
		$this->setTemplate ( $sub );
		$tpl->object->template_dir = $this->template_dir;
		$tpl->object->compile_dir = $this->compile_dir;
		$tpl->smarty->cache_dir = $this->cache_dir;
	}
	
	public function display($page) {
		$this->object->display ( $page );
	}
	
	public function fetch($page) {
		$this->object->fetch ( $page );
	}
	
	public function assign($name, $value) {
		$this->object->assign ( $name, $value );
	}
	
	public function Instance() {
		static $instance = NULL;
		if (! $instance) {
			$instance = new Template ( );
		}
		return $instance;
	}
}
?>